﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class clientLensManager : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            CSUtils.CheckSession();
            PanelInput.Visible = false;
        }
    }


    private void binddataBrandName()
    {
        DropDownListBrand.DataSource = CSUtils.getAllBrandList(false);
        DropDownListBrand.DataBind();
    }

    private void binddataLensName()
    {

        DropDownListLens.DataSource = CSUtils.getAllLensListByRef("内销", DropDownListrRefractive.SelectedValue);
        DropDownListLens.DataBind();
        //DropDownListLens.Items.Insert(0, new ListItem("全部", "-1"));
    }

    protected void Button1_Click(object sender, EventArgs e) 
    {
        PanelInput.Visible = false;
        PanelRef.Visible = false;
        this.binddata();
        LabelErrorMsg.Text = "";
    }

    private void binddata() {
        string clientID = TextBoxClientID.Text;
        GridView1.DataSource = this.getAllClientLens(clientID);
        GridView1.DataBind();        

        PanelAction.Visible = true;
        
    }

    private DataSet getAllClientLens(string clientID)
    {
        string sql =
            "select min(id)as id, client_name, client_type_name, brand_name, lens_name, client_id, brand_id, lens_id from cs_client_lens_detail_view " +
            "where client_id = " + clientID + " " +
            "group by  client_name, client_type_name, brand_name, lens_name,client_id, brand_id, lens_id " +
            "order by client_id, brand_id, lens_id";

        DataSet ds = new DataSet();
        DBConn myDB = new DBConn();
        ds = myDB.getDataSet(sql);
        myDB.Close();
        return ds;
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) {
        GridView1.PageIndex = e.NewPageIndex;
        this.binddata();
    }


    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) {

        LabelErrorMsg.Text = "";
        PanelRef.Visible = false;

        if (e.CommandName.Equals("command_del"))
        {
            PanelInput.Visible = false;
            string id = e.CommandArgument.ToString();

            if (this.deleteClientLens(id))
            {
            }
            else
            {
                JScript.Alert("删除失败！");
            }

            this.binddata();


        }
        else if (e.CommandName.Equals("command_edit"))
        {

            PanelInput.Visible = true;                        
            string ID = e.CommandArgument.ToString();
            //Label1.Text = ID;
            ClientLensVO vo = CSUtils.getClientLens(ID);
            LabelBrandName.Text = vo.BrandName;
            LabelLensName.Text = vo.LensName;
            TextBoxBrandID.Text = vo.BrandID;
            TextBoxLensID.Text = vo.LensID;
            string brandID = vo.BrandID;
            string lensID = vo.LensID;
            GridView2.DataSource = this.getAllLensPrice(brandID, lensID);
            GridView2.DataBind();


            int count = ((DataSet)GridView2.DataSource).Tables[0].Rows.Count;
            if (count > 0)
            {
                ButtonSubmit.Visible = true;
                LabelErrorMsg2.Text = "";
            }
            else
            {
                ButtonSubmit.Visible = false;
                LabelErrorMsg2.Text = "没有对应的光度信息, 请在 <a href='lensPriceManager.aspx' style='color:blue;TEXT-DECORATION: underline'>品牌镜片价格</a> 中添加!";
            }
        }
        else
        {
            this.cleanPanelInput();
        }
        

    }

    private DataSet getAllLensPrice(string brandID, string lensID)
    {
        string clientID = TextBoxClientID.Text;

        string sql =
            //"select price.id, price.brand_id, price.lens_id, price.sphere_begin, price.sphere_end, price.cylinder_begin, price.cylinder_end, price.diameter, price.sale_price, price.agent_price, " +
            //"'1.00'as price_coef, '0' as add_fee " +
            //"from cs_lens_price_base price " +
            //"where 1= 1 {0}" +
            //"order by sphere_begin,sphere_end,cylinder_begin,cylinder_end";
            "select price.id, price.brand_id, price.lens_id, price.sphere_begin, price.sphere_end, price.cylinder_begin, price.cylinder_end, price.diameter, price.sale_price, price.agent_price, " +
            "   isnull(detail.price_coef, 1.00)as price_coef, isnull(detail.add_fee,0)as add_fee " +
            "from cs_lens_price_base price " +
            "left join (select * from cs_client_lens_detail " +
            "   where client_id = " + clientID + " " +
            ")detail on price.id = detail.lens_price_base_id " +
            "where  1=1 {0} " +
            "order by price.sphere_begin,price.sphere_end,price.cylinder_begin,price.cylinder_end";


        string where = "";

        if (!brandID.Equals("-1"))
        {
            where += " and price.brand_id = " + brandID;
        }

        if (!lensID.Equals("-1"))
        {
            where += " and price.lens_id = " + lensID;
        }

        sql = string.Format(sql, where);

        DataSet ds = new DataSet();
        DBConn myDB = new DBConn();
        ds = myDB.getDataSet(sql);
        myDB.Close();
        return ds;
    }


    protected void ButtonSubmit_Click(object sender, EventArgs e) {

        string[] ids = Request.Form.GetValues("lensPriceBaseID");
        string[] priceCoefs = Request.Form.GetValues("priceCoef");
        string[] addFees = Request.Form.GetValues("addFee");


        string clientID = TextBoxClientID.Text;
        string brandID = TextBoxBrandID.Text;
        string lensID = TextBoxLensID.Text;
        string sql =
            "delete from cs_client_lens_detail where client_id={0} and brand_id={1} and lens_id={2};";
        sql = string.Format(sql, clientID, brandID, lensID);
        string sql_insert = 
            "insert into cs_client_lens_detail(client_id, brand_id, lens_id, lens_price_base_id, price_coef, add_fee) " +
            "values(" + clientID + "," + brandID + "," + lensID + "," + "{0}, {1}, {2});";       
         

        for (int i = 0, n = ids.Length; i < n; i++)
        {            
            //Response.Write(priceCoefs[i] + "<br/>");
            sql += string.Format(sql_insert, ids[i], priceCoefs[i], addFees[i]);            
        }

        //Response.Write(sql + "<br/>");

        //update
        DBConn myDB = new DBConn();
        bool ret = myDB.DoTransaction(sql);
        myDB.Close();
        if (ret)
        {
            this.binddata();
            GridView2.DataSource = this.getAllLensPrice(brandID, lensID);
            GridView2.DataBind();
        }
        else
        {
            JScript.Alert("保存失败!");
        }
    }

    protected void LinkButtonAdd_Click(object sender, EventArgs e) {
        PanelInput.Visible = false;        
        PanelRef.Visible = true;
        binddataBrandName();
        binddataLensName();
    }


    private void cleanPanelInput() {
        
    }

    private bool deleteClientLens(string id)
    {
        string clientID = TextBoxClientID.Text;

        ClientLensVO vo = CSUtils.getClientLens(id);        
        string brandID = vo.BrandID;
        string lensID = vo.LensID;

        string sql =
            "delete from cs_client_lens_detail where client_id={0} and brand_id={1} and lens_id={2};";
        sql = string.Format(sql, clientID, brandID, lensID);

        DBConn myDB = new DBConn();
        int tmp = myDB.Delete(sql);
        myDB.Close();
        return (tmp > 0);

    }

    protected void ButtonQuery_Click(object sender, EventArgs e)
    {
        
    }

    protected void DropDownListrRefractive_SelectedIndexChanged(object sender, EventArgs e)
    {
        binddataLensName();
    }

    protected void ButtonRef_Click(object sender, EventArgs e) {

        string clientID = TextBoxClientID.Text;
        string brandID = DropDownListBrand.SelectedValue;
        string lensID = DropDownListLens.SelectedValue;


        //add one
        if (lensID != "-1")
        {
            if (this.doRef(clientID, brandID, lensID))
            {
                LabelErrorMsg.ForeColor = System.Drawing.Color.Blue;
                LabelErrorMsg.Text = "添加成功!";
            }
            else
            {
                LabelErrorMsg.ForeColor = System.Drawing.Color.Red;
                LabelErrorMsg.Text = "添加失败:该客户已有此镜片!";
            }
        }

        this.binddata();

    }

    private bool doRef(string clientID, string brandID, string lensID)
    {
        if (haveThislens(clientID, brandID, lensID)) {
            return false;
        }

        string sql = "insert into cs_client_lens_detail(client_id, brand_id, lens_id) values ({0}, {1}, {2});";

        sql = string.Format(sql, clientID, brandID, lensID);

        DBConn myDB = new DBConn();
        int tmp;
        try
        {
            tmp = myDB.Update(sql);
        }
        catch
        {
            myDB.Close();
            return false;
        }
        myDB.Close();
        return (tmp > 0);
    }


    private bool haveThislens(string clientID, string brandID, string lensID)
    {
        bool have = false;
        string sql =
            "select * from cs_client_lens_detail where client_id={0} and brand_id={1} and lens_id={2}";
        sql = string.Format(sql, clientID, brandID, lensID);

        DBConn myDB = new DBConn();
        SqlDataReader dr = myDB.getDataReader(sql);
        if (dr.Read())
        {
            have = true;
        }
        dr.Close();
        myDB.Close();

        return have;
    }


}
